<?php

namespace app\admin\controller;

use app\admin\model\BrandModel;
use app\admin\validate\BrandValidate;
use think\Request;

class Brand extends Base
{
    /*
     * 列表
     */
    public function index()
    {
        $db         = new BrandModel();
        $brand_name = input('brand_name');
        if (!empty($brand_name)) {
            $db = $db->where('brand_name', $brand_name);
        }
        $list = $db->order('brand_id desc')->paginate();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /*
     * 添加表单
     */
    public function create()
    {
        return $this->fetch();
    }

    /*
     * 保存新建的资源
     */
    public function save(Request $request)
    {
        $data = $request->param();
//        验证表单数据
        $validate = new BrandValidate();
        if (!$validate->check($data)) {
            return ['code' => 0, 'msg' => $validate->getError()];
        }
        $db  = new BrandModel();
        $res = $db->save($data);
        if ($res) {
            return ['code' => 1, 'msg' => '添加成功'];
        } else {
            return ['code' => 0, 'msg' => '添加失败'];
        }
    }

    /*
     * 显示指定的资源
     */
    public function read($id)
    {
        $db   = new BrandModel();
        $info = $db->where('brand_id', $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /*
     * 显示编辑资源表单页
     */
    public function edit($id)
    {
        $db   = new BrandModel();
        $info = $db->where('brand_id', $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /*
     * 保存更新的资源
     */
    public function update(Request $request, $brand_id)
    {
        $data = $request->param();
        $db   = new BrandModel();
        $res  = $db->save($data, ['brand_id' => $brand_id]);
        if ($res) {
            return ['code' => 1, 'msg' => '保存成功', 'url' => url('index')];
        } else {
            return ['code' => 0, 'msg' => '保存失败'];
        }
    }

    /*
     * 删除指定资源
     */
    public function delete()
    {
        $brand_id = input('brand_id');
        $db       = new BrandModel();
        $res      = $db->where('brand_id', $brand_id)->delete();
        if ($res) {
            return ['code' => 1, 'msg' => '删除成功', 'url' => url('index')];
        } else {
            return ['code' => 0, 'msg' => '删除失败'];
        }
    }
}
